package com.job.service;

import com.job.dao.UserInfoDao;
import com.job.pojo.UserInfo;
import com.job.utl.MdFive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Random;

@Service
public class UserInfoServiceImpl  implements UserInfoService{

    @Autowired(required = false)
    UserInfoDao userInfoDao;

    //创建一个加密类工具
    @Autowired
    MdFive mdFive;
    //验证用户账号和密码，返回 登录验证成功 或者 登录验证失败
    @Override
    public String loginVerify(UserInfo user) {
        //验证是否存在用户名
        UserInfo userInfo = userInfoDao.selectByName(user);
        if(userInfo!=null){//用户名存在
            //验证账号和密码是否匹配
            //加密密码
            String pwd = mdFive.encrypt(user.getUserPwd(),userInfo.getSalt());
            user.setUserPwd(pwd);
            UserInfo u = userInfoDao.login(user);
            if(u!=null){
                //把登录信息存进Redis里面,关键字是LoginData
                redisTemplate.opsForValue().set("LoginData",userInfo);
                return "登录验证成功";
            }else {
                return "密码错误";
            }
        }else {
            return  "该账号不存在";
        }
    }

    @Override
    public String zhuce(UserInfo user) {
        //查询用户名是否重名
        int num = userInfoDao.verifyName(user);
        if(num>0){
            return "用户名已被注册";
        }else {
            //加密密码,用户名作为盐值
            String pwd = mdFive.encrypt(user.getUserPwd(),user.getUserName());
            user.setUserPwd(pwd);
            user.setSalt(user.getUserName());
            int n = userInfoDao.zhuce(user);
            if(n>0){
                return "注册成功";
            }
        }
        return "注册失败";
    }

    //获取发件人邮箱
    @Value("${spring.mail.username}")
    String sendEmail;

    //创建发送邮件的对象
    @Autowired
    private JavaMailSender javaMailSender;

    //创建操作Redis库的对象
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public HashMap<String, Object> sendMail(String toEmail, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();

        try {
            //创建普通邮件对象
            SimpleMailMessage message = new SimpleMailMessage();

            //设置发件人邮箱
            message.setFrom(sendEmail);

            //设置收件人邮箱
            message.setTo(toEmail);

            //设置邮件主题
            message.setSubject("学员信息管理系统验证码");

            // 生成随机验证码
            Random rd = new Random();
            String valCode = rd.nextInt(9999)+"";

            //设置邮件正文
            message.setText("您的验证码是："+valCode);

            //发送邮件
            javaMailSender.send(message);

           //发送成功
             // 把验证码存入Redis中
            redisTemplate.opsForValue().set("valCode",valCode);

            map.put("info","发送成功");
            return map;
        } catch (Exception e) {
            System.out.println("发送邮件时发生异常！");
            e.printStackTrace();
        }
        map.put("info","发送邮件异常");
        return map;
    }

    //取出存在Redis里面的验证码用来验证验证码是否正确
    @Override
    public String VerifyCodefunction(UserInfo user) {
        //取出存在Redis里面的验证码
        String verifyCode = redisTemplate.opsForValue().get("valCode")+"";//这里将Object类型转化成Strong类型
        if(verifyCode.equals(user.getVerifyCode())){
            return "验证码正确";
        }
       return "验证码错误";
    }

    @Override
    public String ChangePass(UserInfo user) {
        //先检查旧密码对不对
        //取出Redis里面的用户信息
        UserInfo u = (UserInfo) redisTemplate.opsForValue().get("LoginData");
        String code = u.getUserPwd();//Redis里面的旧密码（加了密的）
        String oldpass = mdFive.encrypt(user.getUserPwd(),u.getSalt());//加密前端给的旧密码
        if(code.equals(oldpass)){//旧密码正确就修改密码
            //加密新密码
            String NewPass = mdFive.encrypt(user.getNewPass(),u.getSalt());
            //设置Id、新密码和盐值
            user.setUserId(u.getUserId());
            user.setUserPwd(NewPass);
            user.setSalt(u.getSalt());
            int k = userInfoDao.ChangePass(user);
            if(k>0){
                return "修改密码成功";
            }else {
                return "修改密码失败";
            }
        }else {
            return "旧密码错误";
        }
    }

    @Override
    public void exit() {

        redisTemplate.delete("LoginData");
        System.out.println("exit");
    }

    @Override
    public String getU() {
        //取出Redis里面的用户信息
        UserInfo u = (UserInfo) redisTemplate.opsForValue().get("LoginData");
        String name = u.getUserName();
        return name;
    }

}
